﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Plexer.ParallelPort;

namespace Plexer.PowerManagement
{
    public class PowerManagement 
    {
        private ParallelPortInfo parallelPortInfo;
        private bool IsEmulated;
        public EventHandler<InputPortPinStatusArgs> OnInputTrigger;

        public PowerManagement(ParallelPortInfo ParallelPortInfo, Boolean isEmulated=false)
        {
            this.IsEmulated = isEmulated;

            if (isEmulated)
                return;

            this.parallelPortInfo = ParallelPortInfo;
            ParallelPort.Manage.parallelportinfo = this.parallelPortInfo;
            ParallelPort.Manage.OnInputStatusTrigger += OnStatusTrigger;            
        }

        public bool isParallelPortAvailble()
        {
            return ParallelPort.Manage.isDriverOpen();
        }

        public void OnStatusTrigger(object sender, InputPortPinStatusArgs args)
        {            
            EventHandler<InputPortPinStatusArgs> resultsTriggerEvent = OnInputTrigger;
            if (resultsTriggerEvent != null)
            {
                resultsTriggerEvent(null, new InputPortPinStatusArgs { PinStatus = args.PinStatus });
            }
        }

        public void TurnAllSwitch(SwitchingState switchstate)
        {
            if (this.IsEmulated)
                return;

            if (switchstate == SwitchingState.On)
                ParallelPort.Manage.TurnAllOn();
            else
                ParallelPort.Manage.TurnAllOff(); 
        }

        public void TurnSpecificSwitch(int SwitchIndex, SwitchingState switchstate, bool ExecuteRightAfter=false)
        {
            if (this.IsEmulated)
                return;

            if (this.parallelPortInfo.Pins.Count() < (parallelPortInfo.MC74HC95_Total * 8))
                throw new Exception("Total number of pins are not equal to total number of MC74HC95 chips x 8");


            PinInfo pin = this.parallelPortInfo.Pins.Where(p => p.PinNo == SwitchIndex).Single();

            int index = this.parallelPortInfo.Pins.IndexOf(pin);
            pin.SwitchState = switchstate;
            this.parallelPortInfo.Pins[index] = pin;

            if (ExecuteRightAfter)
                ParallelPort.Manage.Execute();
        }

        public void GetSwitchStatus()
        {
            ParallelPort.Manage.ReadInputs();           
        }

    }
}
